/*
 * Copyright (c) 2019.  鼎捷软件股份有限公司.All rights reserved.
 */

package com.digiwin.dap.middleware.util;

import com.digiwin.dap.middleware.exception.BusinessException;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.*;

/**
 * @author :  chenzwd
 * @date :    2018/12/11
 */
public class FileUtil {

    /**
     * 读取Jar包中资源文件
     *
     * @param filePath 资源文件路径
     * @return 文件转换后的字符串
     */
    public static String getFileByAbsolutePath(String filePath) {
        try {
            File file = new File(filePath);
            FileReader reader = new FileReader(file);
            BufferedReader bReader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = bReader.readLine()) != null) {
                sb.append(s).append("\n");
            }
            bReader.close();
            return sb.toString();
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 读取Jar包中资源文件
     *
     * @param filePath 资源文件路径
     * @return 文件转换后的字符串
     */
    public static String getFile(String filePath) {
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:" + filePath);
        StringBuffer strBuff = new StringBuffer();
        try (InputStream inputStream = resource.getInputStream()) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String string = null;
            while ((string = bufferedReader.readLine()) != null) {
                strBuff.append(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strBuff.toString();
    }

}
